package cn.controlsys.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * Title: 对象的序列化和反序列化<br/>
 * Description: TODO(用一句话描述该文件做什么)<br/>
 * ClassName： SerializeUtil<br/>
 * Company: Shanghai Controlsys Automation Co., Ltd.<br/>
 * Website: http://www.controlsys.cn<br/>
 * author: gaobitian<br/>
 * date: 2016年9月7日 下午6:04:01<br/>
 * version: V2.0<br/>
 *
 */
public class SerializeUtil {
	private static final Logger logger = LoggerFactory.getLogger(SerializeUtil.class);
	/*
	 * public static byte[] serialize(Object object) { ObjectOutputStream oos =
	 * null; ByteArrayOutputStream baos = null; try { // 序列化 baos = new
	 * ByteArrayOutputStream(); oos = new ObjectOutputStream(baos);
	 * oos.writeObject(object); byte[] bytes = baos.toByteArray(); return bytes;
	 * } catch (Exception e) { e.printStackTrace(); } return null; }
	 * 
	 * public static Object unserialize(byte[] bytes) { ByteArrayInputStream
	 * bais = null; try { // 反序列化 bais = new ByteArrayInputStream(bytes);
	 * ObjectInputStream ois = new ObjectInputStream(bais); return
	 * ois.readObject(); } catch (Exception e) { e.printStackTrace(); } return
	 * null; }
	 */
	/**
	 * <p>
	 * Title: 将字节转换为对象
	 * </p>
	 * <p>
	 * Description: 将字节转换为对象
	 * </p>
	 * <p>
	 * author: gaobitian
	 * <p>
	 * date: 2016年7月14日 下午4:04:12
	 * </p>
	 *
	 * @param bytes
	 * @return Object
	 */
	public static Object ByteToObject(byte[] bytes) {
		Object obj = null;
		try {
			// bytearray to object
			ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
			ObjectInputStream oi = new ObjectInputStream(bi);
			obj = oi.readObject();
			bi.close();
			oi.close();
		} catch (Exception e) {
			logger.error("将字节转换为对象错误", e);
		}
		return obj;

	}

	/**
	 * <p>
	 * Title: 将对像转换为字节
	 * </p>
	 * <p>
	 * Description: 将对像转换为字节
	 * </p>
	 * <p>
	 * author: gaobitian
	 * <p>
	 * date: 2016年7月14日 下午4:07:01
	 * </p>
	 *
	 * @param obj
	 * @return byte[]
	 */
	public static byte[] ObjectToByte(Object obj) {
		byte[] bytes = null;
		try {
			// object to bytearray
			ByteArrayOutputStream bo = new ByteArrayOutputStream();
			ObjectOutputStream oo = new ObjectOutputStream(bo);
			oo.writeObject(obj);

			bytes = bo.toByteArray();

			bo.close();
			oo.close();
		} catch (Exception e) {
			logger.error("将对像转换为字节错误", e);
		}
		return bytes;
	}

}
